package com.A01.sys.controller;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

import com.A01.sys.entity.EmployeeEntity;
import com.A01.sys.entity.UserEntity;
import com.A01.sys.service.EmployeeService;
import com.A01.utils.ContextHolderUtils;
import com.A01.utils.RRException;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


import com.A01.utils.PageUtils;
import com.A01.utils.R;


/**
 * 员工的基本信息
 */
@RestController
@RequestMapping("dev/employee")
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;

    /**
     * 页码方式显示列表
     */
    @RequestMapping("/list")
    public R list(@RequestBody Map<String, Object> params){
        PageUtils page = employeeService.queryPage(params);
        return R.ok().put("page", page);
    }

    /**
     * 查询某一个公司所有员工记录
     */
    @RequestMapping("/listCompanyEmployee")
    public R listCompanyEmployee(){
        List<EmployeeEntity> employeeEntityList= employeeService.listEmployee();
        return R.ok().put("list", employeeEntityList);
    }

    /**
     * 根据id获取员工记录
     */
    @RequestMapping("/info/{id}")
    public R info(@PathVariable("id") Long id){
        EmployeeEntity employee = employeeService.selectById(id);
        return R.ok().put("employee", employee);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    public R save(@RequestBody EmployeeEntity employee){
        //判断输入的身份证号和已存在的身份证号是否重复
        int count = employeeService.selectCount(new EntityWrapper<EmployeeEntity>().eq("id_number", employee.getIdNumber()));
        if (count > 0) {
            throw new RRException("身份证号已存在");
        }
        UserEntity user = ContextHolderUtils.getUser();//根据保存的登录信息确定公司ID
        employee.setCompanyId(user.getCompanyId());
        employeeService.insert(employee);
        return R.ok();
    }

    /**
     * 修改员工信息
     */
    @RequestMapping("/update")
    public R update(@RequestBody EmployeeEntity employee){
        //修正：需要加上和自己的id 不相等的判断，否则每次修改都会判断为身份证号已存在！！！
        int count = employeeService.selectCount(new EntityWrapper<EmployeeEntity>().eq("id_number", employee.getIdNumber()).ne("id",employee.getId()));
        if (count > 0) {
            throw new RRException("身份证号已存在");
        }
        UserEntity user = ContextHolderUtils.getUser();
        employee.setCompanyId(user.getCompanyId());
        employeeService.updateAllColumnById(employee);//全部更新
        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    public R delete(@RequestBody Long[] ids){
        employeeService.deleteBatchIds(Arrays.asList(ids));//批量删除记录
        return R.ok();
    }

}
